const express = require('express');
const request = require('request');
const config = require('./config');
const static = require('express-static');
const path = require('path');
const ejs = require('ejs');

const app = express();
const router = express.Router();

// 静态资源
app.use(static(path.join(__dirname, 'public')));

// 模板引擎
app.set('view engine', 'html');
// 设置模板文件位置 => 项目根路径下views目录为模板文件存放目录
app.set('views', path.join(__dirname, 'views')) ;
app.engine('html', ejs.__express);

/*微信登录*/
var AppID = config.appID;            // 测试号APPID
var AppSecret = config.appScrect;    // 测试号APPSECRET

// 监控路由地址/wx_login
router.get('/wx_login', (req, res) => {
    // 第一步：用户同意授权，获取code
    const router = 'get_wx_access_token';
    // 编码后的回调地址，这里一定要记得加端口号，因为我们在测试号里设置过的
    const return_uri = 'http%3A%2F%2Fhttps://szstyletech.com%3A3000%2Foauth%2F'+router;
    console.log(decodeURIComponent(return_uri));
    const scope = 'snsapi_userinfo';

    // 重定向授权地址，回调页面是return_uri，中间有oauth是因为我下面写了虚拟目录的代理
    res.redirect('https://open.weixin.qq.com/connect/oauth2/authorize?' +
        'appid=' + AppID +
        '&redirect_uri=' + return_uri +
        '&response_type=code' +
        '&scope=' + scope +
        '&state=STATE#wechat_redirect');
});

// get授权页面回调后的code
router.get('/get_wx_access_token', (req, res) => {
    // 第二步：通过code换取网页授权access_token
    var code = req.query.code;
    console.log(code);
    // 请求获取token和用户的openId
    const opt = {
        url:`https://api.weixin.qq.com/sns/oauth2/access_token?appid=${AppID}&secret=${AppSecret}&code=${code}&grant_type=authorization_code`
    };
    request.get(opt, (error,response,body) => {
        if(response.statusCode === 200){
            console.log(body);
            const data = JSON.parse(body);
            const access_token = data.access_token;
            const openid = data.openid;
            // 第三步：利用token和openId请求用户信息
            const opt = {
                url: `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}&lang=zh_CN`
            };
            request.get(opt, (error, response, body) => {
                if(response.statusCode === 200){
                    // 第四步：根据获取的用户信息进行操作
                    const userinfo = JSON.parse(body);
                    console.log('获取信息成功');
                    console.log(userinfo);
                    const str = "<h1>" + userinfo.nickname + " 的个人信息</h1>" +
                                "<p><img src=" + userinfo.headimgurl + "/></p>" +
                                "<p>" + userinfo.city + "," + userinfo.province + "," + userinfo.country + "</p>";
                    //测试
                    res.send(str);
                } else {
                    console.log(response.statusCode);
                }
            });
        }
        else{
            console.log(response.statusCode);
        }
    });
});

// 静态资源下的虚拟目录，即所有的地址都通过http://[host]:3000/oauth来访问
app.use('/oauth', router);

// 模板入口
app.get('/', (req, res) => {
    console.log("主页 GET 请求");
    res.send('Hello GET');
});

// router.get('/*', (req, res) => {
//     res.type('html');
//     res.render('index');
// });

//监听对应主机名及端口
const server = app.listen(3000, 'localhost', () => {
    const host = server.address().address;
    const port = server.address().port;
    console.log('Example app listening at http://%s:%s', host, port);
});
